package cn.com.idmy.cloud.config;

import com.alibaba.fastjson2.support.spring6.data.redis.GenericFastJsonRedisSerializer;
import org.jetbrains.annotations.NotNull;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext.SerializationPair;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@ConditionalOnClass(io.lettuce.core.RedisClient.class)
public class RedisConfig {
    @Bean
    @NotNull
    public RedisTemplate<String, Object> redisTemplate(@NotNull RedisConnectionFactory factory) {
        var template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericFastJsonRedisSerializer());
        template.setHashValueSerializer(new GenericFastJsonRedisSerializer());
        return template;
    }

    @Bean
    @NotNull
    public CacheManager cacheManager(@NotNull RedisConnectionFactory factory) {
        var cacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(factory);
        var keySerialization = SerializationPair.fromSerializer(new StringRedisSerializer());
        var valueSerialization = SerializationPair.fromSerializer(new GenericFastJsonRedisSerializer());
        var cfg = RedisCacheConfiguration.defaultCacheConfig()
                .computePrefixWith(key -> key + ":")
                .entryTtl(Duration.ofMinutes(30L))
                .disableCachingNullValues()
                .serializeKeysWith(keySerialization)
                .serializeValuesWith(valueSerialization);
        return RedisCacheManager.builder(cacheWriter).cacheDefaults(cfg).build();
    }
}
